package com.zhoust.fastdome.exception;


import com.alibaba.fastjson.JSONObject;
import com.zhoust.fastdome.business.entity.CommonLog;
import com.zhoust.fastdome.business.service.CommonLogService;
import com.zhoust.fastdome.common.CommonResponse;
import com.zhoust.fastdome.utils.IPUtils;
import com.zhoust.fastdome.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author zhoust
 * @Date
 * @Desc
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    private final HttpServletRequest request;
    private final CommonLogService commonLogService;

    public ExceptionHandle(HttpServletRequest request,CommonLogService commonLogService) {
        this.request = request;
        this.commonLogService = commonLogService;
    }

    /**
     * 处理未知异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResponse handleException(Exception e){
        e.printStackTrace();
        log.error("系统异常：{}",e);
        CommonLog commonLog = commonLogService.getCommonLog(request, "");
        CommonResponse error = CommonResponse.error("操作异常，日志流水："+commonLog.getLogId());
        error.setLogId(commonLog.getLogId());
        // 失败原因可以不返回前台，根据自己业务需求
        error.setDate(e.getMessage());
        commonLog.setResponseBody(JSONObject.toJSONString(error));
        saveLog(commonLog);
        return error;
    }

    /**
     * 处理主动抛出的自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public CommonResponse handleBusinessException(BusinessException e){
        log.error("自定义异常：{}",e.getErrMassage());
        CommonLog commonLog = commonLogService.getCommonLog(request, "");
        CommonResponse error = CommonResponse.error(e.getErrCode(), e.getErrMassage()+"，日志流水："+commonLog.getLogId());
        error.setLogId(commonLog.getLogId());
        error.setDate(e);
        commonLog.setResponseBody(JSONObject.toJSONString(error));
        saveLog(commonLog);
        return error;
    }


    private void saveLog(CommonLog commonLog){
        commonLogService.save(commonLog);
    }
}
